#include <iostream>
#include "Reactor.hpp"
#include "Listener.hpp"
#include "Channel.hpp"
#include "Protocol.hpp"
#include "Netcal.hpp"
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
        return 1;
    }
    // 构建业务模块
    std::unique_ptr<Cal> cal(std::make_unique<Cal>());
    // 构建协议对象
    std::shared_ptr<Protocol> protocol(std::make_shared<Protocol>([&cal](Request req) -> Response
                                                                  { return cal->Execute(req); }));
    // 构建监听对象
    std::shared_ptr<Connection> listener(std::make_shared<Listener>(std::stoi(argv[1])));
    listener->RegisterHandler([&protocol](std::shared_ptr<Channel> channel)
                              {
    while(true){
    std::string package;
    if (!protocol->Decode(channel->Inbuffer(), &package)) {
        break;               // 报文不完整，先不处理
    }
    else{
        std::string response_str = protocol->Execute(package);
        //添加到outbuffer中
        channel->AppendOutbuffer(response_str);
    } 
    LOG(LogLevel::INFO)<<"匿名函数调用完成";
} });

    // Reactor模块
    std::unique_ptr<Reactor> server(std::make_unique<Reactor>());
    server->Addconnection(listener);
    server->Loop();
    return 0;
}